/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.neuronbit.businessflow.intellij.dialog;

import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.TreeStructureProvider;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.util.TreeChooser;
import com.intellij.ide.util.treeView.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiType;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.ui.*;
import com.intellij.ui.tree.AsyncTreeModel;
import com.intellij.ui.tree.StructureTreeModel;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.AstLoadingFilter;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.mxgraph.model.mxICell;
import com.neuronbit.businessflow.intellij.BpmIcons;
import com.neuronbit.businessflow.intellij.model.FormattedMethodString;
import com.neuronbit.businessflow.intellij.model.JavaMethodTask;
import com.neuronbit.businessflow.intellij.model.SimpleType;
import com.neuronbit.businessflow.intellij.model.Type;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.*;

import static com.neuronbit.businessflow.intellij.dialog.FieldTreeListChooseDialog.NodeType.FIELD;
import static com.neuronbit.businessflow.intellij.dialog.FieldTreeListChooseDialog.NodeType.OUTPUT;
import static com.neuronbit.businessflow.intellij.util.PsiUtils.getFullTypeName;
import static com.neuronbit.businessflow.intellij.util.PsiUtils.isAtomic;

/**
 * This is dialog box for selecting methods of classes
 */
public abstract class FieldTreeListChooseDialog extends DialogWrapper {
    private final @Nullable PsiClass paramClass;
    private JPanel panel = new JPanel(new BorderLayout());
    private final Project myProject;
    private final List<mxICell> cell;
    private final String name;
    private final PsiType expectedType;
    private final List<String> defaultValue;
    private FieldTreeNode mySelectedClass = null;
    private StructureTreeModel<? extends AbstractTreeStructureBase> myModel;

    private final @NotNull TreeChooser.Filter<FieldTreeNode> myClassFilter;
    private Tree myTree;
    private final @NotNull Comparator<? super NodeDescriptor<?>> myComparator;
    private ReturnTypeListPanel returnTypeListPanel;

    /**
     * Instantiates a new Field choose dialog.
     *
     * @param project      the project
     * @param cell         the cell
     * @param name         the name
     * @param expectedType the expected type
     * @param defaultValue the initial field
     */
    public FieldTreeListChooseDialog(@Nullable Project project, @NotNull List<mxICell> cell, String name, @NotNull PsiType expectedType, String defaultValue) {
        super(project);
        this.myProject = project;
        this.cell = cell;
        this.name = name;
        this.expectedType = expectedType;
        if (StringUtils.isNotBlank(defaultValue)) {
            String[] split = defaultValue.split(",");
            List<String> list = new ArrayList<>(split.length);
            for (String s : split) {
                if (StringUtils.isNotBlank(s)) {
                    list.add(s);
                }
            }
            this.defaultValue = list;
        } else {
            this.defaultValue = new ArrayList<>(0);
        }
        setModal(true);
        panel.setOpaque(false);
        //TODO shunyun 2024/4/18:用图上的 y 轴坐标？严格来讲应该用图上的深度
        myComparator = AlphaComparator.INSTANCE;
        myClassFilter = typeFilter();

        paramClass = PsiTypesUtil.getPsiClass(expectedType);

        init();


        // dialog does not exist yet
        SwingUtilities.invokeLater(() -> {
//            selectField(defaultValue);
            returnTypeListPanel.addValue(this.defaultValue);
        });


        SwingUtilities.invokeLater(() -> handleSelectionChanged());
    }

    private TreeChooser.Filter<FieldTreeNode> typeFilter() {
        return node -> {
            if (node == null) {
                return false;
            }
            String nodeClassName = node.getValue().getClazzName().getQualifiedName();
            if (StringUtils.isBlank(nodeClassName)) {
                return false;
            }
            PsiClass nodePsiClass = JavaPsiFacade.getInstance(myProject).findClass(nodeClassName, GlobalSearchScope.allScope(myProject));
            if (nodePsiClass == null) {
                return expectedType.getPresentableText().equals(nodeClassName);
            } else {
                return expectedType.isAssignableFrom(PsiTypesUtil.getClassType(nodePsiClass));
            }
        };
    }

    @Override
    public void doOKAction() {
        super.doOKAction();
    }

    @Override
    public void doCancelAction() {
        super.doCancelAction();
        this.mySelectedClass = null;
    }

    /**
     * Select field.
     *
     * @param initialField the initial field
     */
    public void selectField(List<NodeValue> initialField) {
        // Select element in the tree
        ApplicationManager.getApplication().invokeLater(() -> {
            if (myModel != null && initialField != null) {
                for (NodeValue node : initialField) {
                    myModel.select(node, myTree, path -> {
                        System.out.println(path);
                    });

                }
            }
        }, ModalityState.stateForComponent(getWindow()));
    }

    /**
     * Gets selected.
     *
     * @return the selected
     */
    public List<String> getSelected() {
        return returnTypeListPanel.getValues();
    }

    private @NotNull ModalityState getModalityState() {
        return ModalityState.stateForComponent(getRootPane());
    }

    /**
     * Gets tree.
     *
     * @return the tree
     */
    protected Tree getTree() {
        return myTree;
    }

    /**
     * Calc selected class object [ ].
     *
     * @return the object [ ]
     */
    protected @Nullable Object[] calcSelectedClass() {
        TreePath[] paths = getTree().getSelectionPaths();
        if (null == paths) {
            return null;
        }
        return Arrays.stream(paths)
                .filter(Objects::nonNull)
                .map(p -> (DefaultMutableTreeNode) p.getLastPathComponent())
                //.filter(DefaultMutableTreeNode::isLeaf)
                .map(this::getSelectedFromTreeUserObject)
                .toArray();
    }

    /**
     * Gets selected from tree user object.
     *
     * @param node the node
     * @return the selected from tree user object
     */
    protected Object getSelectedFromTreeUserObject(DefaultMutableTreeNode node) {
        return node.getUserObject();
    }

    /**
     * The enum Node type.
     */
    public enum NodeType {
        /**
         * Root node type.
         */
        ROOT,
        /**
         * Flow node type.
         */
        FLOW,
        /**
         * Task node type.
         */
        TASK,
        /**
         * Output node type.
         */
        OUTPUT,
        /**
         * Field node type.
         */
        FIELD;
    }

    /**
     * The type Node value.
     */
    @Getter
    public static class NodeValue {
        private final NodeType nodeType;
        private final String parentName;
        private final String name;
        private final Type clazzName;
        @Setter
        private FormattedMethodString method;
        @Setter
        private int paramCount;

        /**
         * Instantiates a new Node value.
         *
         * @param nodeType   the node type
         * @param parentName the parent name
         * @param name       the name
         * @param clazzName  the clazz name
         */
        public NodeValue(NodeType nodeType, String parentName, String name, Type clazzName) {
            this.nodeType = nodeType;
            this.parentName = parentName;
            this.name = name;
            this.clazzName = clazzName;
        }

        /**
         * Gets qualified name.
         *
         * @return the qualified name
         */
        public String getQualifiedName() {
            if (StringUtils.isNoneBlank(this.parentName)) {
                return this.parentName + "." + this.name;
            } else {
                return this.name;
            }
        }
    }

    /**
     * The type Field tree node.
     */
    public static abstract class FieldTreeNode extends AbstractTreeNode<NodeValue> {

        /**
         * Instantiates a new Field tree node.
         *
         * @param project the project
         * @param value   the value
         */
        protected FieldTreeNode(Project project, @NotNull NodeValue value) {
            super(project, value);
        }

        /**
         * Process callable.
         *
         * @param list the list
         * @param node the node
         */
        protected void processCallable(ArrayList<AbstractTreeNode<?>> list, JavaMethodTask node) {
            if (null == node.getCallable().getType() || node.getCallable().getMethod() == null || node.getCallable().getMethod().isBlank()) {
                return;
            }
            NodeValue value;
            if (node.getNodeType() == com.neuronbit.businessflow.intellij.model.NodeType.FLOW) {
                value = new NodeValue(NodeType.FLOW, "", node.getName(), node.getCallable().getType());
            } else {
                value = new NodeValue(NodeType.TASK, "", node.getName(), node.getCallable().getType());
            }
            value.setMethod(node.getCallable().getMethod());
            value.setParamCount(node.getCallable().getParams().size());
            list.add(createNode(getProject(), value));
        }

        /**
         * Expand type recursively.
         *
         * @param nodeName the node name
         * @param psiType  the psi type
         * @param list     the list
         */
        protected void expandTypeRecursively(String nodeName, PsiType psiType, ArrayList<AbstractTreeNode<?>> list) {
            PsiClass psiClass = PsiTypesUtil.getPsiClass(psiType);
            if (isAtomic(psiClass)) {
                list.add(createNode(getProject(), new NodeValue(FIELD, this.getValue().getQualifiedName(), nodeName, SimpleType.of(getFullTypeName(psiType)))));
            } else {
                list.add(createNode(getProject(), new NodeValue(OUTPUT, this.getValue().getQualifiedName(), nodeName, SimpleType.of(getFullTypeName(psiType)))));
            }
        }

        /**
         * Create node field tree node.
         *
         * @param project the project
         * @param value   the value
         * @return the field tree node
         */
        protected abstract FieldTreeNode createNode(Project project, NodeValue value);

        /**
         * Extracted first task.
         *
         * @param x    the x
         * @param list the list
         */
        protected void extractedFirstTask(List<mxICell> x, ArrayList<AbstractTreeNode<?>> list) {
            if (null == x) {
                return;
            }
            for (mxICell cell : x) {
                if (cell.getValue() instanceof JavaMethodTask node) {
                    if (node.getCallable() != null) {
                        processCallable(list, node);
                    }
                }
            }
        }

        @Override
        protected void update(@NotNull PresentationData presentationData) {
            AstLoadingFilter.disallowTreeLoading(() -> doUpdate(presentationData));
        }

        private void doUpdate(@NotNull PresentationData data) {
            ApplicationManager.getApplication().runReadAction(() -> {
//                if (!validate()) {
//                    return;
//                }
//
//                final PsiElement value = extractPsiFromValue();
//                LOG.assertTrue(value.isValid());
//
//                int flags = getIconableFlags();
//                Icon icon = null;
//                boolean deprecated = false;
//                try {
//                    icon = value.getIcon(flags);
//                }
//                catch (IndexNotReadyException ignored) {
//                }
//                try {
//                    deprecated = isDeprecated();
//                }
//                catch (IndexNotReadyException ignored) {
//                }
//
//                final Icon tagIcon;
//                final ColoredText tagText;
//                if (!TagManager.isEnabled()) {
//                    tagIcon = getBookmarkIcon(myProject, value);
//                    tagText = null;
//                }
//                else {
//                    var tagIconAndText = TagManager.getTagIconAndText(value);
//                    tagIcon = tagIconAndText.icon();
//                    tagText = tagIconAndText.coloredText();
//                }
//                data.setIcon(withIconMarker(icon, tagIcon));
                NodeValue value = getValue();
                switch (value.getNodeType()) {
                    case FIELD:
                        data.setIcon(PlatformIcons.FIELD_ICON);
                        break;
                    case OUTPUT:
                        data.setIcon(PlatformIcons.RECORD_ICON);
                        break;
                    case FLOW:
                        data.setIcon(BpmIcons.FLOW_ICON);
                        break;
                    case TASK:
                        data.setIcon(PlatformIcons.CLASS_ICON);
                        break;
                }

                data.setPresentableText(value.getName() + (value.getClazzName() == null ? "" : ": " + value.getClazzName().getName()));
//                if (deprecated) {
//                    data.setAttributesKey(CodeInsightColors.DEPRECATED_ATTRIBUTES);
//                }
//                if (tagText != null) {
//                    var fragments = tagText.fragments();
//                    for (ColoredText.Fragment fragment : fragments) {
//                        data.getColoredText().add(new ColoredFragment(fragment.fragmentText(), fragment.fragmentAttributes()));
//                    }
//                    if (!fragments.isEmpty()) {
//                        data.getColoredText().add(new ColoredFragment(myName, getSimpleTextAttributes(data)));
//                    }
//                }
//                updateImpl(data);
//                data.setIcon(patchIcon(myProject, data.getIcon(true), getVirtualFile()));
//                CompoundProjectViewNodeDecorator.get(myProject).decorate(this, data);
//                updateTimestamp();
            });
        }
    }

    /**
     * Create root element object.
     *
     * @return the object
     */
    public abstract @NotNull Object createRootElement();

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        final AbstractTreeStructureBase treeStructure = new AbstractTreeStructureBase(myProject) {

            @Override
            public @NotNull Object getRootElement() {
                return createRootElement();
            }

            @Override
            public void commit() {

            }

            @Override
            public Object getParentElement(@NotNull Object element) {
//                String[] split = null;
//                if (element instanceof NodeValue) {
//                    String parentName = ((NodeValue) element).getParentName();
//                    split = parentName.split("\\.");
//                }
//
//                if (split == null) {
//                    return rootElement;
//                }
//
//                int i = 0;
//                while (i< split.length) {
//                    if (rootElement instanceof FieldTreeNode) {
//                        for (AbstractTreeNode<?> child : ((FieldTreeNode) rootElement).getChildren()) {
//                            if (((NodeValue) child.getValue()).getName().equals(split[i])) {
//                                i++;
//                                rootElement = child;
//                            }
//                        }
//                    }
//                }
//                if (i == split.length) {
//                    return rootElement;
//                } else {
                return super.getParentElement(element);
//                }
            }

            @Override
            public boolean hasSomethingToCommit() {
                return false;
            }

            @Override
            public @Nullable List<TreeStructureProvider> getProviders() {
                TreeStructureProvider provider = new TreeStructureProvider() {

                    @Override
                    public @NotNull Collection<AbstractTreeNode<?>> modify(@NotNull AbstractTreeNode<?> abstractTreeNode,
                                                                           @NotNull Collection<AbstractTreeNode<?>> collection,
                                                                           ViewSettings viewSettings) {
                        return collection;
                    }

                    @Override
                    public @Nullable Object getData(@NotNull Collection<? extends AbstractTreeNode<?>> selected, @NotNull String dataId) {
                        return TreeStructureProvider.super.getData(selected, dataId);
                    }
                };
                return List.of(provider);
            }
        };

        myModel = new StructureTreeModel<>(treeStructure, getDisposable());
        myModel.setComparator(myComparator);
        myTree = new Tree(new AsyncTreeModel(myModel, getDisposable()));
        myTree.setRootVisible(false);
        myTree.setShowsRootHandles(true);
        myTree.expandRow(0);
        myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        myTree.setCellRenderer(new NodeRenderer());

//        JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);


        JPanel treePanel = ToolbarDecorator.createDecorator(myTree)
                .createPanel();
        treePanel.setPreferredSize(JBUI.size(500, 300));
        treePanel.putClientProperty(UIUtil.KEEP_BORDER_SIDES, SideBorder.RIGHT | SideBorder.LEFT | SideBorder.BOTTOM);

        myTree.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (KeyEvent.VK_ENTER == e.getKeyCode()) {
                    doOKAction();
                }
            }
        });
        //与树的展开冲突
//        new DoubleClickListener() {
//            @Override
//            protected boolean onDoubleClick(@NotNull MouseEvent event) {
//                TreePath path = myTree.getPathForLocation(event.getX(), event.getY());
//                if (path != null && myTree.isPathSelected(path)) {
//                    if (mySelectedClass != null) {
//                        methodPanel.addValue(mySelectedClass);
//                    }
//                    return true;
//                }
//                return false;
//            }
//        }.installOn(myTree);

        myTree.addTreeSelectionListener(__ -> handleSelectionChanged());
        myTree.setDragEnabled(true);
        myTree.setTransferHandler(new TreeTransferHandler());

        TreeUIHelper.getInstance().installTreeSpeedSearch(myTree);

        final JBSplitter dummyPanel = new JBSplitter();

        dummyPanel.setFirstComponent(treePanel);

        JPanel component = new JPanel(new BorderLayout());
        this.returnTypeListPanel = new ReturnTypeListPanel(name, expectedType, myProject, myClassFilter);
        component.add(returnTypeListPanel, BorderLayout.CENTER);
        dummyPanel.setSecondComponent(component);
        dummyPanel.setMinimumSize(new Dimension(500, 400));
        dummyPanel.setMaximumSize(new Dimension(500, 400));

        return dummyPanel;
    }

    private void handleSelectionChanged() {
        Object[] selected = calcSelectedClass();
        if (selected == null || selected.length == 0) {
            //setOKActionEnabled(false);
        } else {
            mySelectedClass = (FieldTreeNode) selected[0];
//                ReadAction
//                        .nonBlocking(() -> RELIABLE_DATA_ONLY.ignoreDumbMode(() -> myClassFilter.isAccepted(selectedClass)))
//                        .finishOnUiThread(getModalityState(), isAccepted -> setOKActionEnabled(object != null && isAccepted))
//                        .submit(AppExecutorUtil.getAppExecutorService());

        }
    }

    /**
     * Gets cell.
     *
     * @return the cell
     */
    protected List<mxICell> getCell() {
        return cell;
    }

    /**
     * Gets project.
     *
     * @return the project
     */
    protected Project getProject() {
        return myProject;
    }

    private class TreeTransferHandler extends TransferHandler {
        @Override
        public int getSourceActions(JComponent c) {
            return COPY_OR_MOVE;
        }

        @Override
        protected Transferable createTransferable(JComponent c) {
//            JTree tree = (JTree) c;
//            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            return new TreeNodeTransferable(mySelectedClass);
        }
    }
}
